<template>
  <div class="container">
    <el-dialog
      :visible.sync="isShowDialog"
      :title="`${dataInfo.id?'修改':'新增'}标签`"
      width="500px"
      @close="close"
    >
      <el-form ref="form" :model="tagsInfo" :rules="rules">
        <el-form-item v-if="!$route.query.id" label="所属学科" label-width="80px">
          <el-select v-model="tagsInfo.subjectID">
            <el-option
              v-for="item in subjectList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" label-width="80px" prop="tagName">
          <el-input v-model="tagsInfo.tagName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" @click="close">取消</el-button>
        <el-button size="small" type="primary" @click="submit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects'
import { add, update } from '@/api/hmmm/tags'
export default {
  name: 'TagsAdd',
  props: {
    dataInfo: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      isShowDialog: false,
      subjectList: [],
      tagsInfo: {
        id: null,
        subjectID: null,
        tagName: null
      },
      rules: {
        tagName: [
          { required: true, message: '必填项' }
        ]
      }
    }
  },
  async created() {
    const { data } = await simple()
    this.subjectList = data
  },
  methods: {
    // 显示DIalog对话框
    async showDialog() {
      if (this.dataInfo.id) {
        // const { id, subjectID, tagName } = this.dataInfo
        // this.tagsInfo = { id, subjectID, tagName }
        this.tagsInfo = {
          id: this.dataInfo.id,
          subjectID: this.dataInfo.subjectID,
          tagName: this.dataInfo.tagName
        }
      } else {
        this.tagsInfo = {
          id: null,
          subjectID: +this.$route.query.id || null,
          tagName: null
        }
      }
      this.isShowDialog = true
      await this.$nextTick()
      this.$refs.form.clearValidate()
    },
    // 关闭dialog框，重置表单校验，清除表单
    close() {
      this.isShowDialog = false
      this.$refs.form.resetFields()
      this.tagsInfo = {
        id: null,
        subjectID: null,
        tagName: null
      }
    },
    /* // 下拉框获取焦点时，获取学科简单列表
    async getSubjectList() {
      const { data } = await simple()
      this.subjectList = data
    }, */
    // 添加及修改标签
    async submit() {
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      if (this.dataInfo.id) {
        await update(this.tagsInfo)
      } else {
        await add(this.tagsInfo)
      }
      this.$message.success('操作成功')
      this.isShowDialog = false
      this.$emit('getTagsList')
    }
  }
}
</script>

<style scoped lang='scss'></style>
